package com.simple.weibo.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.simple.weibo.bean.User;
import com.simple.weibo.database.SimpleDatabase;
import com.simple.weibo.database.SimpleDatabaseHelper;
import com.simple.weibo.oauth.OAuth;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author mxf <a href="mailto:maxuefengs@gmail.com">mxf</a>
 *         11-8-15 下午8:51
 * @since version 1.0
 */
public class WeiboContextActivity extends Activity {

    ImageView iv;
    ImageView picView;
    Handler handler;
    Drawable userIcon;
    Drawable picIcon;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weibo_context);
        Bundle b = getIntent().getExtras();
        String id = b.getString("id");
        String userId = b.getString("userId");

        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setTitle("请稍等");
        dialog.setMessage("获取微博信息中...");
        dialog.show();

        iv = (ImageView) findViewById(R.id.user_icon);
        picView = (ImageView) findViewById(R.id.pic);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                 dialog.dismiss();
                if (msg.what == 1) {
                    iv.setImageDrawable(userIcon);
                    iv.invalidate();
                } else {
                    picView.setImageDrawable(picIcon);
                    iv.invalidate();
                    picView.setOnClickListener(new View.OnClickListener(){

                        public void onClick(View v) {
                            Intent intent = new Intent(WeiboContextActivity.this,ViewPicActivity.class);
                            intent.putExtra("url",(String)picView.getTag());
                            startActivity(intent);
                        }
                    });
                }
            }
        };

        showViews(id, userId);
    }


    private void showViews(String id, String userId) {
        SimpleDatabaseHelper helper = new SimpleDatabaseHelper(this, "mydatabase", null, 1);
        SimpleDatabase sd = new SimpleDatabase(helper);
        User user = sd.getUserById(userId);
        sd.close();

        OAuth auth = new OAuth();
        String url = "http://api.t.sina.com.cn/statuses/show/:id.json";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("source", OAuth.appKey));
        params.add(new BasicNameValuePair("id", id));
        HttpResponse response = auth.getServerResponse(user.getAccessToken(), user.getAccessTokenSecret(), url, params);
        System.out.println(response.getStatusLine().getStatusCode());
        if (200 == response.getStatusLine().getStatusCode()) {
            try {
                InputStream is = response.getEntity().getContent();
                Reader reader = new BufferedReader(new InputStreamReader(is), 4000);
                StringBuilder buffer = new StringBuilder((int) response.getEntity().getContentLength());
                try {
                    char[] tmp = new char[1024];
                    int l;
                    while ((l = reader.read(tmp)) != -1) {
                        buffer.append(tmp, 0, l);
                    }
                } finally {
                    reader.close();
                }
                String string = buffer.toString();
                System.out.println(string);

                response.getEntity().consumeContent();
                JSONObject data = new JSONObject(string);
                if (data != null) {
                    JSONObject u = data.getJSONObject("user");
                    String userName = u.getString("screen_name");
                    final String userIcon = u.getString("profile_image_url");
                    String time = data.getString("created_at");
                    String text = data.getString("text");
                    if (data.has("retweeted_status")) {
                        JSONObject r = data.getJSONObject("retweeted_status");
                        text += "\r\n$";
                        JSONObject uu = r.getJSONObject("user");
                        text += uu.getString("screen_name") + ":" + r.getString("text") + "$";
                        if (r.has("bmiddle_pic")) {
                            final String picurl = r.getString("bmiddle_pic");
                            String picurl2 = r.getString("original_pic");

                            picView.setTag(picurl2);

                            new Thread(new Runnable() {
                                public void run() {
                                    URL url = null;
                                    try {
                                        url = new URL(picurl);
                                        picIcon = BitmapDrawable.createFromStream(url.openStream(), "src");
                                        handler.sendEmptyMessage(2);
                                    } catch (MalformedURLException e) {
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                        }
                    }

                    new Thread(new Runnable() {
                        public void run() {
                            URL url = null;
                            try {
                                url = new URL(userIcon);
                                WeiboContextActivity.this.userIcon = BitmapDrawable.createFromStream(url.openStream(), "src");
                                handler.sendEmptyMessage(1);
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                    TextView utv = (TextView) findViewById(R.id.user_name);
                    utv.setText(userName);
                    TextView ttv = (TextView) findViewById(R.id.text);
                    ttv.setText(text, TextView.BufferType.SPANNABLE);
                    MainPageUtils.highLightTex(ttv, "#", "#");
                    MainPageUtils.highLightTex(ttv, "@", ":");
                    MainPageUtils.highLightTex(ttv, "@", " ");
                    MainPageUtils.highLightTex(ttv, "http://", " ");
                    MainPageUtils.highLightTex2(ttv, "$", "$");


                    iv.setImageResource(R.drawable.icon);

                    if (data.has("bmiddle_pic")) {
                        final String picurl = data.getString("bmiddle_pic");
                        String picurl2 = data.getString("original_pic");

                        picView.setTag(picurl2);

                        new Thread(new Runnable() {
                            public void run() {
                                URL url = null;
                                try {
                                    url = new URL(picurl);
                                    picIcon = BitmapDrawable.createFromStream(url.openStream(), "src");
                                    handler.sendEmptyMessage(2);
                                } catch (MalformedURLException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                }
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        url = "http://api.t.sina.com.cn/statuses/counts.json";
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("source", OAuth.appKey));
        params.add(new BasicNameValuePair("ids", id));
        response = auth.getServerResponse(user.getAccessToken(), user.getAccessTokenSecret(), url, params);
        if (200 == response.getStatusLine().getStatusCode()) {
            try {
                InputStream is = response.getEntity().getContent();
                Reader reader = new BufferedReader(new InputStreamReader(is), 4000);
                StringBuilder buffer = new StringBuilder((int) response.getEntity().getContentLength());
                try {
                    char[] tmp = new char[1024];
                    int l;
                    while ((l = reader.read(tmp)) != -1) {
                        buffer.append(tmp, 0, l);
                    }
                } finally {
                    reader.close();
                }
                String string = buffer.toString();
                response.getEntity().consumeContent();
                JSONArray data = new JSONArray(string);
                if (data != null) {
                    if (data.length() > 0) {
                        JSONObject d = data.getJSONObject(0);
                        String comments = d.getString("comments");
                        String rt = d.getString("rt");
                        Button btn_gz = (Button) findViewById(R.id.btn_gz);
                        btn_gz.setText("转发(" + rt + ")");
                        Button btn_pl = (Button) findViewById(R.id.btn_pl);
                        btn_pl.setText("评论(" + comments + ")");
                    }
                }
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}